$(document).ready(function() {
    let taxCalculations = [];
    let portfolios = [];
    let totalPages = 1;
    let currentPage = 1;
    let itemsPerPage = 10;

    // 自定义alert函数
    function customAlert(message) {
        $('#customAlertMessage').text(message);
        $('#customAlertModal').modal('show');
    }

    // 获取所有投资组合用于下拉列表
    function fetchPortfolios() {
        $.ajax({
            url: `/api/portfolios/getAllPortfolios`,
            type: 'GET',
            success: function(data) {
                portfolios = data;
                renderPortfolioSelects();
            },
            error: function(xhr, status, error) {
                console.error('Error fetching portfolios:', error);
            }
        });
    }

    function renderPortfolioSelects() {
        const searchSelect = $('#searchPortfolioId');
        const addSelect = $('#addPortfolioId');
        const editSelect = $('#editPortfolioId');
        
        searchSelect.empty();
        addSelect.empty();
        editSelect.empty();
        
        searchSelect.append('<option value="">全部组合</option>');
        addSelect.append('<option value="">请选择</option>');
        editSelect.append('<option value="">请选择</option>');
        
        portfolios.forEach(portfolio => {
            searchSelect.append(`<option value="${portfolio.id}">${portfolio.portfolioName}</option>`);
            addSelect.append(`<option value="${portfolio.id}">${portfolio.portfolioName}</option>`);
            editSelect.append(`<option value="${portfolio.id}">${portfolio.portfolioName}</option>`);
        });
    }

    function fetchTaxCalculations() {
        const fundCode = $('#searchFundCode').val();
        const portfolioId = $('#searchPortfolioId').val();
        itemsPerPage = parseInt($('#itemsPerPage').val(), 10);
        const queryParams = {
            fundCode: fundCode || '',
            portfolioId: portfolioId || '',
            pageNo: currentPage,
            pageSize: itemsPerPage
        };

        $.ajax({
            url: `/api/taxCalculations/getTaxCalculationsByConditions`,
            type: 'GET',
            data: queryParams,
            success: function(data) {
                if (!data || !data.records) {
                    console.error('Invalid data received:', data);
                    customAlert('获取数据失败，请检查输入条件或稍后重试。');
                    return;
                }

                taxCalculations = data.records;
                totalPages = data.pages;
                renderTaxCalculationTable(taxCalculations);
                updatePagination();
            },
            error: function(xhr, status, error) {
                console.error('Error fetching tax calculations:', error);
                customAlert('获取数据失败，请检查网络连接或稍后重试。');
            }
        });
    }

    function renderTaxCalculationTable(data) {
        const taxCalculationTableBody = $('#taxCalculationTableBody');
        taxCalculationTableBody.empty();

        if (data.length > 0) {
            data.forEach(calculation => {
                const tr = $('<tr>');
                tr.append($('<td>').text(calculation.fundCode || ''));
                tr.append($('<td>').text(calculation.portfolioName || ''));
                tr.append($('<td>').text(calculation.holdingPeriod || ''));
                tr.append($('<td>').text(calculation.profit ? calculation.profit.toFixed(2) : ''));
                tr.append($('<td>').text(calculation.taxRate ? (calculation.taxRate * 100).toFixed(2) + '%' : ''));
                tr.append($('<td>').text(calculation.taxAmount ? calculation.taxAmount.toFixed(2) : ''));
                tr.append($('<td>').text(calculation.createdTime || ''));
                
                const actionsTd = $('<td>');
                actionsTd.html(`
                    <button class="btn btn-sm btn-warning me-2" onclick="editTaxCalculation(${calculation.id})">编辑</button>
                    <button class="btn btn-sm btn-danger" onclick="deleteTaxCalculation(${calculation.id})">删除</button>
                `);
                tr.append(actionsTd);
                taxCalculationTableBody.append(tr);
            });
        } else {
            taxCalculationTableBody.html('<tr><td colspan="8" class="text-center">暂无数据</td></tr>');
        }
    }

    // 更新分页控件
    function updatePagination() {
        // 更新页码显示
        $('#currentPage').text(currentPage);
        $('#totalPages').text(totalPages);
        
        // 更新上一页和下一页按钮状态
        if (currentPage <= 1) {
            $('#prevPage').addClass('disabled');
        } else {
            $('#prevPage').removeClass('disabled');
        }
        
        if (currentPage >= totalPages) {
            $('#nextPage').addClass('disabled');
        } else {
            $('#nextPage').removeClass('disabled');
        }
    }

    function handleSizeChange(newSize) {
        itemsPerPage = newSize;
        currentPage = 1; // 重置到第一页
        fetchTaxCalculations();
    }

    function handleCurrentChange(newPage) {
        // 确保页码在有效范围内
        if (newPage < 1) newPage = 1;
        if (newPage > totalPages) newPage = totalPages;
        
        if (newPage !== currentPage) {
            currentPage = newPage;
            fetchTaxCalculations();
        }
    }

    // 计算应缴税额
    function calculateTaxAmount() {
        const profit = parseFloat($('#addProfit').val()) || 0;
        const taxRate = parseFloat($('#addTaxRate').val()) || 0;
        const taxAmount = profit * taxRate;
        $('#addTaxAmount').val(taxAmount.toFixed(2));
    }

    function calculateEditTaxAmount() {
        const profit = parseFloat($('#editProfit').val()) || 0;
        const taxRate = parseFloat($('#editTaxRate').val()) || 0;
        const taxAmount = profit * taxRate;
        $('#editTaxAmount').val(taxAmount.toFixed(2));
    }

    function addNewTaxCalculation() {
        const transactionId = $('#addTransactionId').val();
        const fundCode = $('#addFundCode').val();
        const portfolioId = $('#addPortfolioId').val();
        const holdingPeriod = $('#addHoldingPeriod').val();
        const profit = $('#addProfit').val();
        const taxRate = $('#addTaxRate').val();

        const newTaxCalculation = {
            transactionId: transactionId || null,
            fundCode: fundCode || null,
            portfolioId: portfolioId || null,
            holdingPeriod: holdingPeriod || null,
            profit: profit || null,
            taxRate: taxRate || null
        };

        $.ajax({
            url: `/api/taxCalculations/addTaxCalculation`,
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(newTaxCalculation),
            success: function(data) {
                $('#addTaxCalculationForm')[0].reset();
                $('#addTaxCalculationModal').modal('hide');
                fetchTaxCalculations();
                customAlert('新增成功');
            },
            error: function(xhr, status, error) {
                console.error('Error adding tax calculation:', error);
                customAlert('新增税务计算失败');
            }
        });
    }

    function saveEditTaxCalculation() {
        const taxCalculationId = $('#editTaxCalculationId').val();
        const transactionId = $('#editTransactionId').val();
        const fundCode = $('#editFundCode').val();
        const portfolioId = $('#editPortfolioId').val();
        const holdingPeriod = $('#editHoldingPeriod').val();
        const profit = $('#editProfit').val();
        const taxRate = $('#editTaxRate').val();

        const updatedTaxCalculation = {
            id: taxCalculationId,
            transactionId: transactionId || null,
            fundCode: fundCode || null,
            portfolioId: portfolioId || null,
            holdingPeriod: holdingPeriod || null,
            profit: profit || null,
            taxRate: taxRate || null
        };

        $.ajax({
            url: `/api/taxCalculations/updateTaxCalculation`,
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(updatedTaxCalculation),
            success: function(data) {
                $('#editTaxCalculationModal').modal('hide');
                fetchTaxCalculations();
                customAlert('信息更新成功');
            },
            error: function(xhr, status, error) {
                console.error('Error updating tax calculation:', error);
                customAlert('更新税务计算失败');
            }
        });
    }

    function deleteTaxCalculation(id) {
        if (confirm('确定要删除该税务计算吗？')) {
            $.ajax({
                url: `/api/taxCalculations/deleteTaxCalculation/${id}`,
                type: 'POST',
                success: function() {
                    fetchTaxCalculations();
                    customAlert('删除成功');
                },
                error: function(xhr, status, error) {
                    console.error('Error deleting tax calculation:', error);
                    customAlert('删除税务计算失败');
                }
            });
        }
    }

    // 全局函数供HTML调用
    window.editTaxCalculation = function(id) {
        const calculation = taxCalculations.find(p => p.id == id);
        if (calculation) {
            $('#editTaxCalculationId').val(calculation.id);
            $('#editTransactionId').val(calculation.transactionId || '');
            $('#editFundCode').val(calculation.fundCode || '');
            $('#editPortfolioId').val(calculation.portfolioId || '');
            $('#editHoldingPeriod').val(calculation.holdingPeriod || '');
            $('#editProfit').val(calculation.profit || '');
            $('#editTaxRate').val(calculation.taxRate || '');
            calculateEditTaxAmount();
            $('#editTaxCalculationModal').modal('show');
        }
    };

    window.deleteTaxCalculation = deleteTaxCalculation;

    // 事件绑定
    $('#fetchTaxCalculationsButton').on('click', fetchTaxCalculations);
    $('#saveAddTaxCalculation').on('click', addNewTaxCalculation);
    $('#saveEditTaxCalculation').on('click', saveEditTaxCalculation);

    // 税额计算事件绑定
    $('#addProfit, #addTaxRate').on('input', calculateTaxAmount);
    $('#editProfit, #editTaxRate').on('input', calculateEditTaxAmount);

    $('#itemsPerPage').on('change', function() {
        handleSizeChange(parseInt($(this).val(), 10));
    });

    $('#pPage').on('click', function(e) { 
        e.preventDefault();
        if (currentPage > 1) {
            handleCurrentChange(currentPage - 1); 
        }
    });
    
    $('#nPage').on('click', function(e) { 
        e.preventDefault();
        if (currentPage < totalPages) {
            handleCurrentChange(currentPage + 1); 
        }
    });

    // 初始化
    fetchPortfolios();
    fetchTaxCalculations();
});